package com.atguigu.gulimail.coupon.dubbo;

import com.atguigu.common.service.coupon.CouponDubboService;
import com.atguigu.common.utils.R;
import com.atguigu.gulimail.coupon.dao.SeckillSessionDao;
import com.atguigu.gulimail.coupon.dao.SeckillSkuRelationDao;
import com.atguigu.gulimail.coupon.entity.SeckillSessionEntity;
import com.atguigu.gulimail.coupon.entity.SeckillSkuRelationEntity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fangy
 * @date 2022-10-24 15:31
 */
@DubboService
public class CouponDubboServiceImpl implements CouponDubboService {


    @Autowired
    SeckillSessionDao seckillSessionDao;

    @Autowired
    SeckillSkuRelationDao seckillSkuRelationDao;


    @Override
    public R getLates3DaySession() {

        List<SeckillSessionEntity> sessions = seckillSessionDao.selectList(new QueryWrapper<SeckillSessionEntity>().between("start_time", startTime(), endTime()));

        if(sessions != null && sessions.size()>0){

            List<SeckillSessionEntity> promotion_session_id1 = sessions.stream().map(session -> {

                Long id = session.getId();

                List<SeckillSkuRelationEntity> promotion_session_id = seckillSkuRelationDao.selectList(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", id));

                session.setRelationSkus(promotion_session_id);

                return session;
            }).collect(Collectors.toList());

            return R.ok().setData(promotion_session_id1);
        }
        return null;
    }

    public String startTime(){

        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        LocalDateTime start = LocalDateTime.of(now, min);

        String format = start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        return format;
    }

    public String endTime(){

        LocalDate now = LocalDate.now();
        LocalDate localDate = now.plusDays(2);

        LocalDateTime end = LocalDateTime.of(localDate, LocalTime.MAX);

        String format = end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        return format;
    }
}
